<template>
  <view class="container">
    <!-- 病史记录 -->
    <view class="section medical-history-section">
      <view class="section-header" @click="formCollapsed = !formCollapsed">
        <text class="section-title">{{ t('medical.disease_record_title') }}</text>
        <view class="flex-spacer"></view>
        <text class="collapse-arrow">{{ formCollapsed ? '▼' : '▲' }}</text>
      </view>

      <view v-show="!formCollapsed" class="section-content">
        <!-- 既往病史 - 多选 -->
        <view class="form-row full-width">
          <view class="form-label full-width">{{ t('medical.disease_record') }}</view>
          <view class="multi-select-container">
            <view 
              v-for="item in optionalInfo.select_item" 
              :key="item.id"
              class="multi-select-item"
              :class="{ 'selected': isSelected('disease_record', item.id) }"
              @click="onMultiSelectChange('disease_record', item.id)"
            >
              <text class="item-label">{{ getCurrentLanguage() === 'zh' ? item.label : item.value }}</text>
            </view>
          </view>
          
          <!-- 显示已选择的项目 -->
          <view v-if="formData.disease_record.length > 0" class="selected-items">
            <text class="selected-title">{{ t('medical.selected_items') }}</text>
            <text v-for="(itemId, index) in formData.disease_record" :key="index" class="selected-tag">
              {{ getItemLabel(itemId) }}
              <text class="remove-tag" @click="removeSelectedItem('disease_record', itemId)" :aria-label="t('common.delete')">×</text>
            </text>
          </view>
        </view>
        
        <!-- 选填信息部分 -->
        <view class="form-row full-width">
          <!-- 其他已知疾病 -->
          <view class="optional-form-item">
            <view class="optional-label">{{ t('medical.other_known_diseases') }}</view>
            <textarea 
              v-model="formData.other_known_diseases" 
              class="optional-textarea" 
              :placeholder="t('medical.other_known_diseases_placeholder')"
            />
          </view>
          
          <!-- 既往针灸或干针不良反应 -->
          <view class="optional-form-item">
            <view class="optional-label">{{ t('medical.adverse_reaction') }}</view>
            <textarea 
              v-model="formData.adverse_reaction" 
              class="optional-textarea" 
              :placeholder="t('medical.adverse_reaction_placeholder')"
            />
          </view>
          
          <!-- 过敏史 -->
          <view class="optional-form-item">
            <view class="optional-label">{{ t('medical.allergy_desc') }}</view>
            <textarea 
              v-model="formData.allergy_desc" 
              class="optional-textarea" 
              :placeholder="t('medical.allergy_desc_placeholder')"
            />
          </view>
          
          <!-- 当前用药 -->
          <view class="optional-form-item">
            <view class="optional-label">{{ t('medical.medication_desc') }}</view>
            <textarea 
              v-model="formData.medication_desc" 
              class="optional-textarea" 
              :placeholder="t('medical.medication_desc_placeholder')"
            />
          </view>
        </view>
      </view>
    </view>

    <!-- 固定底部提交按钮 -->
    <view class="fixed-bottom-btn">
      <button class="fill-btn" @click="goToNextStep">{{ t('medical.next_step') }}</button>
    </view>
  </view>
</template>

<script>
import { useI18n } from 'vue-i18n'
import { getOptionalInfo } from '@/api/medical.js'
import { useUserStore } from '@/store/user.js'

export default {
  data() {
    return {
      formCollapsed: false,
      memberInfo: {}, // 会员信息
      formData: {
        patient_id: '',         // 患者ID
        // 病史记录字段
        disease_record: [],    // 既往病史 - 多选
        // 选填信息字段
        other_known_diseases: '',   // 其他已知疾病
        adverse_reaction: '', // 既往针灸或干针不良反应
        allergy_desc: '',   // 过敏史详情
        medication_desc: '',  // 当前用药
      },
      // 可选信息数据
      optionalInfo: {
        select_item: [], // 需要用户选择的项目
        optional_item: [], // 可选项目
        write_item: [], // 需要书写的项目
        pain_description: [] // 疼痛描述
      }
    }
  },
  
  setup() {
    const { t } = useI18n()
    const userStore = useUserStore()
    
    // 动态设置页面标题以支持国际化
    if (typeof uni !== 'undefined' && uni.setNavigationBarTitle) {
      uni.setNavigationBarTitle({
        title: t('medical.disease_record_title')
      })
    }
    return { t, userStore }
  },
  
  onReady() {
    // 进入页面时设置国际化标题
    if (typeof this.t === 'function') {
      uni.setNavigationBarTitle({
        title: this.t('medical.disease_record_title')
      })
    }
  },

  computed: {
    userStore() {
      return useUserStore()
    },
    userInfo() {
      return this.userStore.userInfo
    }
  },

  onShow() {
    // 设置页面标题
    if (typeof this.t === 'function') {
      uni.setNavigationBarTitle({
        title: this.t('medical.disease_record_title')
      })
    }
    
    // 从本地存储获取患者信息
    const patientInfo = uni.getStorageSync('medical_patient_info');
    if (patientInfo && patientInfo.patient_id) {
      this.memberInfo = patientInfo.patient_info;
      this.formData.patient_id = patientInfo.patient_id;
    }
    
    // 获取可选信息
    this.loadOptionalInfo();
    
    // 调试信息
    // console.log('medical-history - 患者信息:', this.memberInfo);
    // console.log('medical-history - 患者ID:', this.formData.patient_id);
  },

  methods: {
    // 加载可选信息
    async loadOptionalInfo() {
      try {
        const response = await getOptionalInfo();
        if (response && response.result) {
          this.optionalInfo = response.result;
        }
      } catch (error) {
        console.error('获取可选信息失败:', error);
      }
    },
    
    // 处理多选变化
    onMultiSelectChange(field, value) {
      if (this.formData[field].includes(value)) {
        // 如果已选中，则移除
        this.formData[field] = this.formData[field].filter(item => item !== value);
      } else {
        // 如果未选中，则添加
        this.formData[field].push(value);
      }
    },
    
    // 检查是否选中
    isSelected(field, value) {
      return this.formData[field].includes(value);
    },
    
    // 根据ID获取项目标签
    getItemLabel(itemId) {
      const item = this.optionalInfo.select_item.find(item => item.id === itemId);
      return item ? item.label : '';
    },
    
    // 移除已选择的项目
    removeSelectedItem(field, itemId) {
      this.formData[field] = this.formData[field].filter(id => id !== itemId);
    },
    
    // 获取当前语言
    getCurrentLanguage() {
      return this.$i18n.locale || 'zh';
    },

    // 跳转到下一步 - 当前病情和患者同意声明页面
    goToNextStep() {
      // 保存病史记录数据到本地存储
      const medicalHistoryData = {
        ...this.formData,
        patient_info: this.memberInfo
      };
      
      // console.log('medical-history - 准备传递的数据:', medicalHistoryData);
      
      // 将病史记录数据存储到本地，供下一步页面使用
      uni.setStorageSync('medical_history_data', medicalHistoryData);
      
      // 跳转到当前病情和患者同意声明页面
      uni.navigateTo({
        url: '/pages/medicine/current-condition'
      });
    }
  }
}
</script>

<style scoped>
.container {
  background: #fff;
  min-height: 100vh;
  padding-bottom: 140rpx;
  overflow-x: hidden;
  box-sizing: border-box;
}

.section {
  background: #fafafa;
  margin: 24rpx;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 8rpx #eee;
  padding: 24rpx;
  display: flex;
  flex-direction: column;
  gap: 16rpx;
  max-width: calc(100% - 48rpx);
  box-sizing: border-box;
  overflow: hidden;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
  cursor: pointer;
  user-select: none;
}

.section-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #1976d2;
}

.flex-spacer {
  flex: 1;
}

.collapse-arrow {
  color: #888;
  font-size: 24rpx;
}

.section-content {
  margin-top: 20rpx;
}

.form-row.full-width {
  flex-direction: column;
  align-items: flex-start;
  width: 100%;
  min-width: 100%;
}

.form-label.full-width {
  width: 100%;
  font-weight: bold;
  color: #1976d2;
  font-size: 26rpx;
  margin-bottom: 12rpx;
}

/* 多选组件样式 */
.multi-select-container {
  width: 100%;
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200rpx, 1fr));
  gap: 20rpx;
  margin-top: 16rpx;
}

.multi-select-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20rpx 16rpx;
  border: 2rpx solid #e3f2fd;
  border-radius: 12rpx;
  background: #fff;
  cursor: pointer;
  transition: all 0.3s ease;
  text-align: center;
  min-height: 120rpx;
  box-sizing: border-box;
}

.multi-select-item:hover {
  border-color: #bbdefb;
  transform: translateY(-2rpx) scale(1.01);
  box-shadow: 0 6rpx 20rpx rgba(25, 118, 210, 0.15);
}

.multi-select-item.selected {
  border-color: #1976d2;
  background: #e3f2fd;
  color: #1976d2;
  transform: scale(1.02);
  box-shadow: 0 4rpx 16rpx rgba(25, 118, 210, 0.2);
}

.multi-select-item.selected .item-label {
  color: #1976d2;
  font-weight: 700;
}

.item-label {
  font-size: 26rpx;
  color: #333;
  font-weight: 600;
  margin-bottom: 12rpx;
  line-height: 1.3;
  text-align: center;
  word-break: break-word;
}

/* 已选择项目样式 */
.selected-items {
  width: 100%;
  margin-top: 16rpx;
  padding: 16rpx;
  background: #f8f9fa;
  border-radius: 8rpx;
  border: 1rpx solid #e9ecef;
}

.selected-title {
  font-size: 24rpx;
  color: #1976d2;
  font-weight: 600;
  margin-right: 16rpx;
}

.selected-tag {
  display: inline-block;
  background: #1976d2;
  color: #fff;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  font-size: 22rpx;
  margin: 8rpx 8rpx 8rpx 0;
  position: relative;
}

.remove-tag {
  margin-left: 8rpx;
  font-weight: bold;
  cursor: pointer;
  padding: 0 4rpx;
}

.remove-tag:hover {
  color: #ffebee;
}

/* 选填信息样式 */
.optional-form-item {
  width: 100%;
  min-width: 100%;
  margin-bottom: 24rpx;
  padding: 20rpx;
  background: #f8f9fa;
  border-radius: 12rpx;
  border: 1rpx solid #e9ecef;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
}

.optional-label {
  font-size: 26rpx;
  color: #1976d2;
  font-weight: 600;
  margin-bottom: 16rpx;
  line-height: 1.4;
}

.optional-textarea {
  width: 100%;
  padding: 16rpx;
  border: 1rpx solid #bbdefb;
  border-radius: 8rpx;
  background: #fff;
  font-size: 26rpx;
  color: #333;
  transition: border-color 0.3s ease;
  min-height: 80rpx;
  max-height: 120rpx;
  resize: vertical;
  box-sizing: border-box;
  line-height: 1.4;
  display: block;
  min-width: 0;
  flex: 1;
}

.optional-textarea:focus {
  border-color: #1976d2;
  outline: none;
}

.fixed-bottom-btn {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background: #fff;
  padding: 16rpx 24rpx 32rpx 24rpx;
  z-index: 100;
  box-shadow: 0 -2rpx 8rpx #eee;
}

.fill-btn {
  width: 100%;
  background: #1976d2;
  color: #fff;
  border-radius: 8rpx;
  font-size: 30rpx;
  height: 80rpx;
  line-height: 80rpx;
  display: block;
}

/* 响应式布局调整 */
@media screen and (max-width: 750rpx) {
  .multi-select-container {
    grid-template-columns: repeat(2, 1fr);
    gap: 16rpx;
  }
  
  .multi-select-item {
    min-height: 100rpx;
    padding: 16rpx 12rpx;
  }
  
  .item-label {
    font-size: 24rpx;
    margin-bottom: 8rpx;
  }
}

@media screen and (min-width: 751rpx) {
  .multi-select-container {
    grid-template-columns: repeat(3, 1fr);
    gap: 24rpx;
  }
  
  .multi-select-item {
    min-height: 140rpx;
    padding: 24rpx 20rpx;
  }
  
  .item-label {
    font-size: 28rpx;
    margin-bottom: 16rpx;
  }
}
</style>
